package com.pzh.vue.controller;


import com.pzh.vue.mapper.SysUserMapper;
import com.pzh.vue.pojo.SysUser;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzh.vue.common.Constants;
import com.pzh.vue.common.Result;
import com.pzh.vue.exception.ServiceException;
import com.pzh.vue.pojo.Course;
import com.pzh.vue.service.ICourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xzh
 * @since 2022-04-04
 */
@RestController
@RequestMapping("/course")
public class CourseController {
     @Autowired
      private ICourseService courseService;
     @Autowired
     private SysUserMapper userMapper;
     @GetMapping
     public Result findAll(){
        List<Course> list = courseService.list();
        Result result=new Result();
        result.setStatus(200);
        result.setData(list);
        return result;
        }
     @PostMapping(value = "/update")
     public Result saveCourse(@RequestBody Course course ){
        System.out.println(course);
        try {
        courseService.saveOrUpdate(course);
        }catch (Exception e){
        throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success();
        }
     @GetMapping("/page")
     public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam(defaultValue = "") String courseName){
        IPage<Course> page=new Page<Course>(pageNum,pageSize);
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        if (!(courseName==null)){
        queryWrapper.like("course_name",courseName);
        }
        try {
        courseService.page(page, queryWrapper);
        }catch (Exception e){
        throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success(page);
        }
    @GetMapping("/dropPage")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam(defaultValue = "") String userName,String bug){
        IPage<Course> page=new Page<Course>(pageNum,pageSize);
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        String courseName = userMapper.isEmptyCourse(userName);
            queryWrapper.eq("course_name",courseName);
        try {
            courseService.page(page, queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success(page);
    }
    /**
     * 选课
     * @param courseName 课程名
     * @param userName 学生名
     * @return
     */
     @GetMapping("/select")
     public Result selectCourse(@RequestParam String courseName,@RequestParam String userName,@RequestParam Integer maxNum,@RequestParam Integer selectNum){
          if (!(userMapper.isEmptyCourse(userName)==null)){
              return Result.error(Constants.CODE_900,"错误！！！请先退课");
          }
          selectNum=selectNum+1;//选一次加一次
         if (selectNum<=maxNum){
           userMapper.selectCourse(courseName, userName);//选课操作
           courseService.updateSelectNum(selectNum,courseName);//更新已选人数
           return Result.success();
         }
         else {
             return Result.error(Constants.CODE_800,"课程可选人数已满");
         }

     }
    @GetMapping("/drop")
    public Result selectCourse(@RequestParam String courseName,@RequestParam String userName,@RequestParam Integer selectNum){
        if ((userMapper.isEmptyCourse(userName)==null)){
            return Result.error(Constants.CODE_1000,"错误！！！请先选课");
        }
        selectNum=selectNum-1;//选一次减一次
        if (selectNum>=0){
            userMapper.dropCourse(null, userName);//退课操作  将课程设为空
            courseService.updateSelectNum(selectNum,courseName);//更新已选人数
            return Result.success();
        }
        else {
            return Result.error(Constants.CODE_9999,"非法操作");
        }

    }
    //增加和更新方法
    @PostMapping("/save")
    public boolean save(@RequestBody Course course) {
        //如果不是管理员不允许更新敏感信息
      /*  if (!(c.checkRoot(sysUser.getUsername()))){
            sysUser.setScores(null);
        }*/
        QueryWrapper<Course> courseName = new QueryWrapper<Course>().eq("course_name", course.getCourseName());
        Course one = courseService.getOne(courseName,false);
        if (one==null){
            course.setId(null);
        }
        else {course.setId(one.getId());}
        boolean save = courseService.saveOrUpdate(course);
        return save;
    }
      @DeleteMapping("/{id}")
      public Result delete(@PathVariable Integer id){
        try {
      courseService.removeById(id);
        }catch (Exception e){
        throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success();
        }
@GetMapping("/export")
public void exportExel(HttpServletResponse response) throws IOException {
        //查询所有用户
        List<Course> list=courseService.list();
        System.out.println("我在运行了");
        //在内存操作，写到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);
        //默认配置
        writer.write(list,true);
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        //设置标题
        String fileName= URLEncoder.encode("用户信息","UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();
        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
        }

/**
 * 导入excel
 * @param file
 */
@PostMapping("/import")
public void importExcel(MultipartFile file) throws IOException {
        //1.第一种 头必须和实体一样
        //文件处理成io流
        InputStream in=file.getInputStream();
        //io流给ExcelReader
        ExcelReader excelReader=ExcelUtil.getReader(in);
        //读取数据且转化为list
        List<Course> list=excelReader.readAll(Course.class);
        //第二种导入方式
        //忽略第一行头
       /* List<List<Object>> list=excelReader.read(1);
        List<SysUser> listUser= CollUtil.newArrayList();
        for (List<Object> row: list) {
            SysUser user=new SysUser();
            user.setUsername(row.get(0).toString());
            *//*****类似一一对应*****//*
        }*/
        //批量注册进数据库
        courseService.saveBatch(list);
        }
}

